#include<bits/stdc++.h>
using namespace std;
char mx[1005][1005];
char vis[1005][1005];
int mv[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int r,c;
int s_x,s_y;
//定义地图每个点的状态
typedef struct node{
	//坐标
	int x,y;
	//步数
	int step;
	//状态，1为火
	int flag;
}node;
queue<node> q;
int ans = -1;
void bfs(){
	//把人推入队列
	q.push({s_x,s_y,0,0});
	while(!q.empty()){
		node head = q.front();
		q.pop();
		//人满足逃离的条件
		if(head.flag == 0 && (head.x == 1 || head.y == 1 || head.x == r || head.y == c)){
			ans = head.step + 1;
			return ;
		}
		for(int i = 0;i < 4;i++){
			int xx = head.x + mv[i][0];
			int yy = head.y + mv[i][1];
			if(xx >= 1 && yy >= 1 && xx <= r && yy <= c && mx[xx][yy] != '#' && !vis[xx][yy]){
				vis[xx][yy] = 1;//走过的不再走
				node next;
				next.x = xx,next.y = yy,next.step = head.step + 1,next.flag = head.flag;
				q.push(next);
			}
		}
	}
}
int main(){
	int t;
	cin >> t;
	while(t--){
		ans = -1;
		cin >> r >> c;
		//清空队列
		while(!q.empty()){
			q.pop();
		}
		memset(vis,0,sizeof(vis));
		//读入地图，并且读入火的位置和人的起始位置
		for(int i = 1;i <= r;i++){
			for(int j = 1;j <= c;j++){
				cin >> mx[i][j];
				if(mx[i][j] == 'J'){
					s_x = i,s_y = j;
				}
				if(mx[i][j] == 'F'){
					//把火推入队列
					q.push({i,j,0,1});
				}
			}
		}
		bfs();
		if(ans == -1){
			cout << "IMPOSSIBLE\n";
		}else{
			cout << ans << "\n";
		}
	}
}